// 1.引入express
const express=require('express');
//1.引入body-parser
const bodyParser=require('body-parser');

// 2.路径处理模块
const path=require('path');

// 3.创建web服务器
const app=express();

//2.body-parser添加到项目app中去,把bodyParser注册到APP下面去
app.use(bodyParser.urlencoded({ extended: false }))  //false接收的值为字符串或者数组，true则为任意类型
// parse application/json    
app.use(bodyParser.json())   //解析json格式

// 4.静态资源访问服务功能
app.use(express.static(path.join(__dirname,'public')))

// get请求
app.get('/ajaxGet',(request,response)=>{
  response.setHeader("Access-Control-Allow-Origin", "*");
  // response.status(400).send("hello ajax get!");
  response.send("hello ajax get!");
})

// 处理get方法的JSON数据
app.get('/ajaxGetData',(request,response)=>{
  response.setHeader("Access-Control-Allow-Origin","*");
  let json={"name":"jason","age":18};
  response.send(json);
});

app.get('/deliverData',(resquest,response)=>{
  response.setHeader("Access-Control-Allow-Origin","*");
  // 拿到客户端传递过来的参数
  let str=resquest.query;
  response.send(str)
});

app.post("/post",(request,response)=>{
  response.setHeader("Access-Control-Allow-Origin","*");
  let str=request.body;
  response.send(request.body);
  // response.send("hello ajax post");
});

app.post("/json",(request,response)=>{
  response.setHeader("Access-Control-Allow-Origin","*");
  response.send("json");
})

app.get('/getReadyState',(request,response)=>{
  response.setHeader("Access-Control-Allow-Origin","*");
  response.send("hello");
});

// ajax错误处理
app.get('/error',(req,res)=>{
  res.setHeader("Access-Control-Allow-Origin","*");
  // 设置响应状态码
  // console.log(abc);
  res.status(400).send("ajax error");
})

// 5.监听端口
app.listen(3000,function(){
  console.log("服务器启动正常");
})

// 6.控制台输出提示
console.log("服务器启动正常");